package sample.stormax.pres.news.adapters;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sample.stormax.pres.news.NewsDetailActivity;
import sample.stormax.pres.news.R;
import sample.stormax.pres.news.beans.Data;
import sample.stormax.pres.news.utils.cache.CacheUtils;
import sample.stormax.pres.news.utils.sqlite.FavouriteSQLiteImpl;
import sample.stormax.pres.news.utils.sqlite.ISQLiteOperation;

import static android.os.Environment.isExternalStorageRemovable;

/**
 * Created by StormAX on 2018/6/28 16:00.
 * Mail yuanmenglong97@qq.com
 */

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
    private static final String TAG = "NewsAdapter";

    //新闻数据列表
    private List<Data> dataList;

    //缓存方法
    private static CacheUtils cacheUtils;

    //MainActivity
    private final Context context;

    //数据库操作类
    private ISQLiteOperation favouriteOp;

    //是否是收藏夹适配器
    private boolean isFavourite = false;

    //当前视图中是否选中收藏
    private List<Boolean> checkedList;

    //唯一的收藏夹适配器
    private static NewsAdapter favouriteAdapter;

    //当前适配器的类型
    private String type;
    //新闻适配器类型Map，存放已创建的NewsAdapter
    private static Map<String, NewsAdapter> newsAdapters = new HashMap<>();
    //谁添加了数据
    private static Map<Data, String> whereTheDataFrom = new HashMap<>();

    //当前视图
    private View view;

    //新闻适配器
    private NewsAdapter(Context context, List<Data> dataList, String type) {
        this.dataList = dataList;
        this.context = context;
        this.type = type;
        //设置收藏按键值列表
        Boolean[] checked = new Boolean[dataList.size()];
        Arrays.fill(checked, false);
        checkedList = new ArrayList<>();
        checkedList.addAll(Arrays.asList(checked));
        //initialize cache
        cacheUtils = CacheUtils.newInstance(context);
        //获取数据库操作类
        favouriteOp = FavouriteSQLiteImpl.newInstance(context);
    }

    //收藏夹构造器
    private NewsAdapter(Context context) {
        this.context = context;
        //initialize cache
        cacheUtils = CacheUtils.newInstance(context);
        //获取数据库操作类
        favouriteOp = FavouriteSQLiteImpl.newInstance(context);
        //从数据库获取喜欢的列表
        dataList = favouriteOp.queryAll();
    }

    /**
     * 获取新闻适配器
     *
     * @param context  上下文对象
     * @param dataList 新闻数据列表
     * @param type     新闻数据类型
     * @return 新闻适配器
     */
    public static NewsAdapter getNewsAdapter(Context context, List<Data> dataList, String type) {
        Log.d(TAG, "new NewsAdapter " + type);
        NewsAdapter newsAdapter = new NewsAdapter(context, dataList, type);
        newsAdapters.put(type, newsAdapter);
        return newsAdapter;
    }


    /**
     * 获取收藏夹适配器
     *
     * @param context 上下文
     * @return 收藏夹适配器单例
     */
    public static NewsAdapter getFavouriteAdapter(Context context) {
        if (favouriteAdapter == null) {
            favouriteAdapter = new NewsAdapter(context);
            favouriteAdapter.setFavourite(true);
        }
        return favouriteAdapter;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (dataList != null) {
            final Data data = dataList.get(position);
            holder.summary.setText(data.getTitle());
            holder.date.setText(data.getDate());
            holder.data = data;
            holder.position = position;
            holder.thumbnail.setTag(data.getUniquekey());
            //加载图片
            cacheUtils.loadBitmap(data, holder.thumbnail);

            //除收藏夹页外显示喜欢checkbox
            if (!isFavourite) {
                //RecyclerView复用，导致checkbox选择错位
                holder.favouriteBtn.setChecked(checkedList.get(position));
                holder.favouriteBtn.setTag(checkedList.get(position));
                holder.favouriteBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CheckBox cb = (CheckBox) v;
                        Log.d(TAG,dataList.indexOf(data)+"");
                        checkedList.set(dataList.indexOf(data), cb.isChecked());
                        Log.d(TAG,Arrays.toString(checkedList.toArray()));
                        if (cb.isChecked()) {
                            //添加收藏夹来源
                            whereTheDataFrom.put(data, type);
                            favouriteOp.addFavourite(data);
                            favouriteAdapter.addItem(data);
                        } else {
                            //删除收藏夹来源
                            whereTheDataFrom.remove(data);
                            favouriteOp.deleteFavourite(data);
                            int index = favouriteAdapter.getDataList().indexOf(data);
                            if (index != -1)
                                favouriteAdapter.removeAt(index);
                        }
                    }
                });
            } else holder.favouriteBtn.setVisibility(View.INVISIBLE);


        } else return;
    }

    @Override
    public int getItemCount() {
        return dataList != null ? dataList.size() : 0;
    }

    //视图删除Item操作
    public void removeAt(int position) {
        if (checkedList != null) {
            checkedList.remove(position);
            Log.d(TAG,Arrays.toString(checkedList.toArray()));
        }
        dataList.remove(position);
        notifyItemRemoved(position);
        notifyItemChanged(position);
    }

    //视图中取消收藏
    public void cancelFavourite(int position) {
        checkedList.set(position, false);
        notifyItemChanged(position);
    }

    //视图添加Item操作
    public void addItem(Data data) {
        if (isFavourite) {
            if (dataList == null) dataList = new ArrayList<>();
            dataList.add(data);
            notifyItemInserted(dataList.size());
            notifyItemChanged(dataList.size());
        }
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        final View mView;
        final ImageView thumbnail;
        final TextView summary;
        final TextView date;
        final ImageButton closeBtn;
        final CheckBox favouriteBtn;

        long lastClick = System.currentTimeMillis();
        Data data;

        int position;

        public ViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
            thumbnail = mView.findViewById(R.id.thumbnail_image);
            summary = mView.findViewById(R.id.summary_text);
            date = mView.findViewById(R.id.date_text);
            closeBtn = mView.findViewById(R.id.close_btn);
            favouriteBtn = mView.findViewById(R.id.favourite_btn);

            // 小于16ms adapter仍未刷新完成,会导致adapterPosition和layoutPosition出现不一致，会导致一些逻辑上的错误
            closeBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    long clickTime = System.currentTimeMillis();
                    //可接受的延迟时间200ms
                    if (clickTime - lastClick < 200)
                    return;
                    lastClick = clickTime;

                    if (isFavourite) {
                        //数据来源的adapter,将收藏取消
                        String type = whereTheDataFrom.get(data);
                        Log.d(TAG, "source " + type);
                        //获取到收藏夹数据来源的adapter
                        NewsAdapter source = newsAdapters.get(type);
                        if (source != null) {
                            //删除适配器中的项目
                            int position = source.getDataList().indexOf(data);
                            Log.d(TAG, "delete" + position);
                            source.cancelFavourite(position);
                        }
                        //删除数据来源map中的键值对
                        whereTheDataFrom.remove(data);
                        //收藏夹数据库中删除数据
                        favouriteOp.deleteFavourite(data);
                        Log.d(TAG, "source num" + whereTheDataFrom.size());
                    } else if (!isFavourite && favouriteBtn.isChecked()) {
                        favouriteOp.deleteFavourite(data);
                        int index = favouriteAdapter.getDataList().indexOf(data);
                        if (index != -1)
                            favouriteAdapter.removeAt(favouriteAdapter.getDataList().indexOf(data));
                    }
                    //删除当前视图中的item
                    removeAt(getLayoutPosition());

                }
            });

            mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, NewsDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", data);
                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            });
        }
    }

    public void setDataList(List<Data> dataList) {
        this.dataList = dataList;
    }

    public List<Data> getDataList() {
        return dataList;
    }

    public List<Boolean> getCheckedList() {
        return checkedList;
    }

    public void setFavourite(boolean favourite) {
        isFavourite = favourite;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        NewsAdapter that = (NewsAdapter) o;

        if (type != null ? !type.equals(that.type) : that.type != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return type != null ? type.hashCode() : 0;
    }
}
